<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addRole">新增角色</el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table border stripe style="width: 100%" :data="rolesList">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column label="角色名" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="setRoles(scope.row)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRoles(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoles(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination
              :current-page="query.page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" class="tab-pane">
            <el-alert title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改" type="info" show-icon :closable="false" />
            <el-form label-width="120px" :model="companyInfo" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfo.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfo.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyInfo.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="roleDialogCloseFn"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="cancleRoles">取消</el-button>
            <el-button size="small" type="primary" @click="roleSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%"
        @close="setVisible"
      >
        <assign-permission :permission-list="permissionList" :perm-ids="permIds" @close="setVisible" @addPerEV="addPerFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRolesAPI, getCompanyInfoAPI, addRoleAPI, getRoleIdAPI, updateRoleAPI,
  getUserProfileAPI, deleteRoleAPI, getPermissionListAPI, transTree, assignPermAPI } from '@/api'
import AssignPermission from './components/assignPermission.vue'

export default {
  name: 'Setting',
  components: {
    AssignPermission
  },
  data() {
    return {
      activeName: 'first',
      query: {
        page: 1, // 当前页面
        pagesize: 10 // 页面显示的条数
      },
      rolesList: [], // 角色列表
      total: 0, // 角色数据总条数
      companyInfo: {},
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      isEdit: false,
      dialogVisible: false,
      roleId: '',
      permissionList: [],
      permIds: []
    }
  },
  created() {
    this.getRolesList()
    this.getCompanyInfo()
    this.getPermissionList()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange(val) {
      this.query.pagesize = val
      this.getRolesList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(val) {
      this.query.page = val
      this.getRolesList()
    },

    // 获取角色列表
    async getRolesList() {
      const res = await getRolesAPI(this.query)
      this.rolesList = res.data.rows
      this.total = res.data.total
    },

    roleDialogCloseFn() {
      this.$refs.roleForm.resetFields()
    },

    // 获取公司信息
    async getCompanyInfo() {
      const { data: { companyId }} = await getUserProfileAPI()
      const res = await getCompanyInfoAPI(companyId)
      this.companyInfo = res.data
    },

    // 添加角色
    addRole() {
      this.isEdit = false
      this.showDialog = true
    },

    // 取消添加角色
    cancleRoles() {
      this.showDialog = false
    },

    // 确认添加角色
    roleSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          let res = null
          if (this.isEdit) {
            res = await updateRoleAPI(this.roleForm)
          } else {
            res = await addRoleAPI(this.roleForm)
          }
          if (res.success) {
            this.$message.success(res.message)
            this.getRolesList()
            this.showDialog = false
          } else {
            this.$message.error(res.message)
          }
        } else {
          return false
        }
      })
    },

    // 设置权限
    async setRoles(row) {
      this.roleId = row.id
      this.dialogVisible = true
      const res = await getRoleIdAPI(this.roleId)
      this.permIds = res.data.permIds
    },

    // 编辑角色
    async editRoles(data) {
      this.isEdit = true
      // 调用接口，获取需要编辑的角色数据
      const res = await getRoleIdAPI(data.id)
      if (!res.success) return this.$message.error(res.message)
      this.roleForm = res.data
      // 让弹框展示
      this.showDialog = true
    },

    // 删除角色
    delRoles(data) {
      this.$confirm('确定删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteRoleAPI(data.id)
        if (res.success) {
          if (this.rolesList.length === 1 && this.query.page > 1) {
            this.query.page--
          }
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.getRolesList()
      })
    },

    async getPermissionList() {
      const res = await getPermissionListAPI()
      this.permissionList = transTree(res.data, '0')
    },

    setVisible() {
      this.dialogVisible = false
      this.permIds = []
    },

    // 确认添加权限
    async addPerFn(permIds) {
      const res = await assignPermAPI({
        id: this.roleId,
        permIds: permIds
      })
      if (res.success) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
